package com.company.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.bookstore.common.formatUtils.FormatUtils;
import com.company.bookstore.entities.book_module.Book;
import com.company.bookstore.entities.order_module.Order;
import com.company.bookstore.mapper.order_module.LogisticsMapper;
import com.company.bookstore.mapper.order_module.OrderMapper;
import com.company.bookstore.qo.order_module.OrderQo;
import com.company.bookstore.service.order_module.LogisticsService;
import com.company.bookstore.service.order_module.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.log.LogFormatUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 赵云霞
 * @since 2020-09-08
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    LogisticsService logisticsService;
    //添加订单
    @Override
    public List<Order> saveOrder(int uid, OrderQo[] orderQos) {


        List<Order> list = new ArrayList<>();

        for (int i = 0; i < orderQos.length; i++) {
            if (orderQos[i]==null){
                continue;
            }
            //转换double的值为两位小数
            double total = orderQos[i].getPrice() * orderQos[i].getNum();
            BigDecimal b = new BigDecimal(total);
            double df = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            Order order = Order.builder()
                    .orderNum(UUID.randomUUID().toString())//订单号随机生成
                    .status(0)//订单状态刚生成默认是下单未支付
                    .price(orderQos[i].getPrice())//订单价格，前台获取
                    .num(orderQos[i].getNum())
                    .totalPrice(df)
                    .createTime(new Date(System.currentTimeMillis()))
                    .fkUserId(uid)
                    .fkBookId(orderQos[i].getFkBookId())
                    .orderAdd(orderQos[i].getOrderAdd())//默认地址,前台传过来的默认id
                    .deleted(0)//默认未取消
                    .build();

            list.add(order);
        }
        saveBatch(list);

        return list;
    }

    @Resource
    OrderMapper orderMapper;
    //根据订单oid 查询订单详情 包括了用户，图书信息
    @Override
    public Order getOrderDetail(int oid) {

        Order order = orderMapper.getOrderDetail(oid);
        //判断status
        if(order.getStatus()==0&&isTimeOut(order.getCreateTime().getTime())){
            order.setStatus(5);
            updateById(order);
        }

        if(order.getBook()!=null){
            FormatUtils.formatOneImgUrl(order.getBook());
        }
        if(logisticsService.getLogistics(oid)!=null){
            order.setLogistics(logisticsService.getLogistics(oid));
        }
        order.setAddress(orderMapper.getOrderAddress(order.getId()));

        return order;
    }


    //查询用户下的所有订单
    @Override
    public List<Order> getOrderByUid(int uid) {
        List<Order> list = orderMapper.getOrderList(uid);
        List<Order> listArr = new ArrayList<>();

        for(int i=0;i<list.size();i++){
           if(list.get(i).getBook()!=null){
               FormatUtils.formatOneImgUrl(list.get(i).getBook());
           }
           if(list.get(i).getStatus()==0&&isTimeOut(list.get(i).getCreateTime().getTime())) {
               list.get(i).setStatus(5);
               listArr.add(list.get(i));
           }
        }
        updateBatchById(listArr);

        return list;
    }

    private boolean isTimeOut(long oldTime){
        long l = System.currentTimeMillis() - oldTime;
        return (int) (l / 1000 / 60 / 60) >= 1;
    }

    //删除单个订单
    @Override
    public boolean delete(int uid, int oid) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>()
                .eq("fk_user_id",uid).eq("id",oid);

        return remove(queryWrapper);
    }

    //修改订单状态
    @Override
    public List<Order> updateStatus(Order[] orders) {

        List<Order> list = new ArrayList<>();

        for (int i = 0; i < orders.length; i++) {
            if (orders[i] == null) {
                continue;
            }
            if(orders[i].getStatus()==4){
                orders[i].setFinishTime(new Date(System.currentTimeMillis()));
            }
            else if(orders[i].getStatus()==3){
                orders[i].setDeleted(1);
                orders[i].setFinishTime(new Date(System.currentTimeMillis()));
            }else if(orders[i].getStatus()==2){
                logisticsService.createLogistics(orders[i].getId());//状态发货，创建物流
            }
            else ;

            list.add(orders[i]);
        }
        updateBatchById(list);

        return list;
    }


    //修改订单数据,订单评价，订单地址，订单数量
    @Override
    public Order updateDetails(OrderQo orderQo,int oid) {


        Order order = new Order();

         if(orderQo.getId()==null){
            orderQo.setId(oid);
        }
        BeanUtils.copyProperties(orderQo,order);

        updateById(order);

        return getById(oid);
    }


    //模糊，条件，分页查询
    @Override
    public Page<Order> getOrderPage(long current, long limit) {
        //创建一个page对象
        Page<Order> pageOrder = new Page<>(current,limit);

        //条件分页查询
        return page(pageOrder);

    }
}